package com.useeinfo.oa.modules.repair.biz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.biz.CrudBiz;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.func.file.FileUtils;
import com.useeinfo.framework.sugar.tools.*;
import com.useeinfo.oa.common.config.ConstantKeyFilePath;
import com.useeinfo.oa.common.enums.ResultEnums;
import com.useeinfo.oa.common.utils.NumberUtil;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.*;
import com.useeinfo.oa.modules.base.entity.*;
import com.useeinfo.oa.modules.base.enums.MessageTypeEnum;
import com.useeinfo.oa.modules.base.enums.NodeTypeEnum;
import com.useeinfo.oa.modules.base.enums.ResourceTypeEnum;
import com.useeinfo.oa.modules.base.vo.MessageVO;
import com.useeinfo.oa.modules.repair.dao.RepairOrderDao;
import com.useeinfo.oa.modules.repair.dao.RepairWorkLogDao;
import com.useeinfo.oa.modules.repair.entity.*;
import com.useeinfo.oa.modules.repair.enums.*;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.biz.SystemAuthorityBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.biz.UserDeviceBiz;
import com.useeinfo.oa.modules.security.entity.SystemAuthority;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.entity.UserDevice;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import com.useeinfo.oa.modules.threadUtil.ThreadUtils;
import com.useeinfo.oa.modules.wuHanCommon.base.entity.Warning;
import com.useeinfo.oa.modules.wuHanCommon.base.entity.WarningDetail;
import com.useeinfo.oa.modules.wuHanCommon.base.entity.WarningGroup;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@Service
public class AutomaticRepairBiz extends CrudBiz<RepairOrderDao, RepairOrder> {

    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private SystemUserBiz systemUserBiz;
    @Autowired
    private RepairOrderBiz repairOrderBiz;
    @Autowired
    private RepairPartnerBiz repairPartnerBiz;
    @Autowired
    private SystemAuthorityBiz systemAuthorityBiz;
    @Autowired
    private RepairFocusBiz repairFocusBiz;
    @Autowired
    private RepairOrderLogBiz repairOrderLogBiz;
    @Autowired
    private RepairWorkLogDao repairWorkLogDao;
    @Autowired
    private RepairWorkLogBiz repairWorkLogBiz;
    @Autowired
    private DictInfoBiz dictInfoBiz;
    @Autowired
    private ResourceBiz resourceBiz;
    @Autowired
    private TroubleCatBiz troubleCatBiz;
    @Autowired
    private PositionBiz positionBiz;
    @Autowired
    private OrganizationBiz organizationBiz;
    @Autowired
    private AreaBiz areaBiz;
    @Autowired
    private FacilityCatBiz facilityCatBiz;
    @Autowired
    private UserDeviceBiz userDeviceBiz;
    @Autowired
    private MessageBiz messageBiz;
    @Autowired
    private RepairLevelBiz repairLevelBiz;
    @Autowired
    private AuditFlowBiz auditFlowBiz;

    private static final String autoIntAuditFlow = Configuration.getConfigurationByName("autoIntAuditFlow");

    /**
     * 获取自动报修工单
     *
     * @param pageIndex   页码
     * @param pageSize    页数
     * @param status      状态
     * @param searchParam 搜索项
     * @param systemUser  用户
     * @param enterprise  企业
     * @param date        时间
     * @return
     */
    public ResultDto getAutomaticRepair(String pageIndex, String pageSize, String status, String searchParam, SystemUser systemUser, Enterprise enterprise, String date) {
        systemUser = systemUserBiz.findModel(systemUser.getId());
        Position position = systemUser.getPosition(enterprise, systemUser.getPositionSet());
        Set<Long> areaIds = new HashSet<>();
        if (systemUser.getAreaSet() != null) {
            for (Area area : systemUser.getAreaSet()) {
                areaIds.add(area.getId());
            }
        }

        Set<SystemUserOrganization> systemUserOrganizationSet = systemUser.getSystemUserOrganizationSet();
        //所属部门
        Organization organization = null;
        boolean leader = false;
        if (CollectionUtils.isNotEmpty(systemUserOrganizationSet)) {
            organization = systemUserOrganizationSet.iterator().next().getOrganization();
            leader = systemUserOrganizationSet.iterator().next().isLeader();
        }


        String enterpriseId = StringConverters.null2String(enterprise.getId());
        String userId = StringConverters.null2String(systemUser.getId());
        return ResultUtil.success(dao.getAutomaticRepair(pageIndex, pageSize, enterpriseId, userId, areaIds, position == null ? null : StringConverters.null2String(position.getId()), status, leader, organization, searchParam, date));
    }

    //实时工时
    public ResultDto nowWorkHours(String id) {
        JSONObject jsonObject = new JSONObject();
        long totalHours = 0;
        RepairOrder repairOrder = dao.findModel(StringConverters.null2Long(id));
        if (repairOrder == null) {
            jsonObject.put("totalHours", totalHours);
            jsonObject.put("receiveHours", totalHours);
            return ResultUtil.success(jsonObject);
        }
        if (repairOrder.getRepairOrderStatusEnum().getCode().equals("UNFINISHED") || repairOrder.getRepairOrderStatusEnum().getCode().equals("WAIT_CONFIRM_FAULT")) {
            totalHours = DateTimeUtils.getDistanceMinutes(repairOrder.getPresenceTime(), new Date());
        }
        jsonObject.put("totalHours", repairOrder.getTotalWorkingHours() + totalHours);
        jsonObject.put("receiveHours", repairOrder.getWorkingHours() + totalHours);
        return ResultUtil.success(jsonObject);
    }

    /**
     * 报修单详情
     *
     * @param repairOrderId
     * @return
     */
    public ResultDto automaticDetail(String repairOrderId) {
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (StringUtils.isBlank(repairOrderId)) {
            return ResultUtil.error("参数错误");
        }
        RepairOrder repairOrder = repairOrderBiz.findModel(StringConverters.null2Long(repairOrderId));
        if (repairOrder == null) {
            return ResultUtil.error("参数错误");
        }
        JSONObject jsonObject = repairOrder.toJSONObject();

        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("repairOrderId", repairOrderId);

        //工时计算
        net.sf.json.JSONObject workingTime = net.sf.json.JSONObject.fromObject(nowWorkHours(repairOrderId).getData());
        if (repairOrder.getRepairOrderStatusEnum().getCode().equals("UNFINISHED") || repairOrder.getRepairOrderStatusEnum().getCode().equals("REJECTED") || repairOrder.getRepairOrderStatusEnum().getCode().equals("WAIT_CONFIRM_FAULT")) {
            jsonObject.put("totalWorkingHours", workingTime.get("totalHours"));//总工时
            jsonObject.put("workingHour", workingTime.get("receiveHours"));//我的工时
            jsonObject.put("workingHours", workingTime.get("receiveHours"));//我的工时
        }
        jsonObject.put("beforeHours", repairOrder.getWorkingHours());//退回重修前的工时
        jsonObject.put("beforeTotalHours", repairOrder.getTotalWorkingHours());//退回重修前的总工时

        JSONArray partnerArray = new JSONArray();
        List<RepairPartner> repairPartners = repairPartnerBiz.findList(queryParam);
        repairPartners.sort((o1, o2) -> o1.getId() < o2.getId() ? -1 : 1);
        if (CollectionUtils.isNotEmpty(repairPartners)) {
            for (RepairPartner repairPartner : repairPartners) {
                JSONObject partnerObject = new JSONObject();
                partnerObject.put("userName", repairPartner.getPartner().getUserName());
                partnerObject.put("userId", repairPartner.getPartner().getId());
                partnerObject.put("partnerId", repairPartner.getId());
                partnerObject.put("workingHours", repairPartner.getWorkingHours());
                partnerObject.put("deleteStatus", repairPartner.isDeleteStatus());
                partnerArray.add(partnerObject);
            }
        }
        jsonObject.put("partner", partnerArray);
        JSONArray jsonArray = new JSONArray();
        String statusCode = repairOrder.getRepairOrderStatusEnum().getCode();
        JSONArray flowArray = JSONArray.parseArray(repairOrder.getFlow());
        int auditLevel = repairOrder.getAuditLevel();
        systemUser = systemUserBiz.findModel(systemUser.getId());
        Set<SystemUserOrganization> systemUserOrganizationSet = systemUser.getSystemUserOrganizationSet();
        boolean leader = false;
        Organization organization = null;
        if (CollectionUtils.isNotEmpty(systemUserOrganizationSet)) {
            //所属部门
            leader = systemUserOrganizationSet.iterator().next().isLeader();
            organization = systemUserOrganizationSet.iterator().next().getOrganization();
        }

        String takingAuthority = "ROLE_AUTO_REPAIR_ORDER_TAKING";
        String auditAuthority = "ROLE_AUTO_REPAIR_ORDER_AUDIT";
        String assignAuthorityName = "ROLE_AUTO_REPAIR_ORDER_ASSIGN";
        if ("WAIT_TAKING".equals(statusCode)) {
            if (systemAuthorityBiz.hasAuthAuthority(assignAuthorityName, systemUser.getId(), sessionEnterprise.getId())) {
                jsonArray.add("assignButton");
            }
            if (repairOrder.getFacility() != null) {
                jsonArray.add("logButton");
            }

            if (systemAuthorityBiz.hasAuthAuthority(takingAuthority, systemUser.getId(), sessionEnterprise.getId())) {
                jsonArray.add("takingButton");
            }

        } else if ("IN_AUDITING".equals(statusCode)) {

            if (systemAuthorityBiz.hasAuthAuthority(auditAuthority, systemUser.getId(), sessionEnterprise.getId())) {
                if (organization != null) {
                    if (repairOrder.getAuditUser() != null || repairOrder.getAuditPosition() != null) {
                        if ((repairOrder.getAuditOrganization() == organization && repairOrder.getAuditUser() == systemUser)) {
                            jsonArray.add("passButton");
                            jsonArray.add("rejectButton");
                        } else if (repairOrder.getAuditOrganization() == organization && repairOrder.getAuditPosition() == systemUser.getPosition(sessionEnterprise, systemUser.getPositionSet())) {
                            jsonArray.add("passButton");
                            jsonArray.add("rejectButton");
                        }
                    }
                }

                if (flowArray.size() > 0 && auditLevel + 1 == flowArray.size()) {
                    jsonObject.put("final", true);
                } else {
                    jsonObject.put("final", false);
                }
            }
        } else if ("WAIT_PRESENCE".equals(statusCode)) {
            if (repairOrder.getReceiveUser() != null && repairOrder.getReceiveUser() == systemUser) {
                jsonArray.add("presenceButton");
            }
        } else if ("WAIT_CONFIRM_FAULT".equals(statusCode)) {
            jsonArray.add("confirmButton");
        } else if ("UNFINISHED".equals(statusCode)) {
            if (repairOrder.getReceiveUser() != null && repairOrder.getReceiveUser() == systemUser) {
                jsonArray.add("submitButton");
                jsonArray.add("saveButton");
            }
        } else if ("REJECTED".equals(statusCode)) {
            if (repairOrder.getReceiveUser() != null && repairOrder.getReceiveUser() == systemUser) {
                jsonArray.add("presenceButton");
            }
        }
        jsonObject.put("buttons", jsonArray);
        jsonObject.put("isFocus", isFocus(repairOrderId, systemUser, sessionEnterprise));
        jsonObject.put("auditLog", aduitLog(repairOrderId, sessionEnterprise));
        return ResultUtil.success(jsonObject);

    }


    public Boolean isFocus(String repairOrderId, SystemUser systemUser, Enterprise enterprise) {
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("systemUserId", StringConverters.null2String(systemUser.getId()));
        queryParam.getSqlMap().put("repairOrderId", repairOrderId);
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
        List<RepairFocus> repairFocusList = repairFocusBiz.findList(queryParam);
        if (CollectionUtils.isEmpty(repairFocusList)) {
            return false;
        }
        return true;
    }

    /**
     * 审批记录
     */
    public JSONArray aduitLog(String repairOrderId, Enterprise enterprise) {
        JSONArray result = new JSONArray();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("repairOrderId", repairOrderId);
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
        queryParam.getSqlMap().put("repairOrderLogOperation", "AUDIT,REJECT");
        queryParam.setSqlOrder(" order by id  ");
        RepairOrder repairOrder = repairOrderBiz.findModel(StringConverters.null2Long(repairOrderId));
        List<RepairOrderLog> list = repairOrderLogBiz.findList(queryParam);
        for (RepairOrderLog repairOrderLog : list) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userName", StringConverters.null2String(repairOrderLog.getUserName()));
            if ("AUDIT".equals(repairOrderLog.getRepairOrderLogOperationEnum().getCode())) {
                jsonObject.put("operation", "审批通过");
                jsonObject.put("status", "AUDIT");
            } else if ("REJECT".equals(repairOrderLog.getRepairOrderLogOperationEnum().getCode())) {
                jsonObject.put("operation", "审批驳回");
                jsonObject.put("status", "REJECT");
                jsonObject.put("remark", StringConverters.null2String(repairOrderLog.getRemark()));
            }
            result.add(jsonObject);
        }
        return result;
    }


    /**
     * 关注/取消关注
     */
    public ResultDto focus(String repairOrderId, Boolean type) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || enterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (type) {
            //关注
            RepairFocus repairFocus = new RepairFocus();
            repairFocus.setEnterprise(enterprise);
            repairFocus.setSystemUser(systemUser);
            repairFocus.setRepairOrder(dao.findModel(StringConverters.null2Long(repairOrderId)));
            repairFocusBiz.addOrUpdate(repairFocus);
        } else {
            //取消关注
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("systemUserId", StringConverters.null2String(systemUser.getId()));
            queryParam.getSqlMap().put("repairOrderId", repairOrderId);
            queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
            List<RepairFocus> repairFocusList = repairFocusBiz.findList(queryParam);
            for (RepairFocus repairFocus : repairFocusList) {
                repairFocusBiz.delete(repairFocus.getId());
            }
        }
        return ResultUtil.success();
    }

    /**
     * 新增工单日志
     *
     * @param logId          日志id
     * @param workLogCatId
     * @param workLogLevelId
     * @param workContent
     * @param photos
     * @param repairOrderId
     * @return
     */
    public ResultDto addLog(String logId, String workLogCatId, String workLogLevelId, String workContent, String photos, String repairOrderId) {
        RepairWorkLog repairWorkLog;
        if (com.useeinfo.framework.sugar.func.lang.StringUtils.isNoneBlank(logId)) {
            repairWorkLog = repairWorkLogDao.findModel(StringConverters.null2Long(logId));
        } else {
            repairWorkLog = new RepairWorkLog();
        }

        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        repairWorkLog.setCode(repairWorkLogDao.getCode(StringConverters.null2String(sessionEnterprise.getId())));
        repairWorkLog.setWorkContent(StringConverters.null2String(workContent));

        if (com.useeinfo.framework.sugar.func.lang.StringUtils.isNotBlank(photos)) {
            JSONArray jsonArray = JSONArray.parseArray(photos);
            if (jsonArray.size() > 0) {
                Set<Resource> resources = new HashSet<>();
                for (Object id : jsonArray) {
                    Resource resource = resourceBiz.findModel(StringConverters.null2Long(id));
                    resources.add(resource);
                }
                repairWorkLog.setLogPhoto(resources);
            }
        }

        repairWorkLog.setSystemUser(systemUser);

        if (com.useeinfo.framework.sugar.func.lang.StringUtils.isNotBlank(workLogCatId)) {
            DictInfo workLogCat = dictInfoBiz.findModel(StringConverters.null2Long(workLogCatId));
            repairWorkLog.setWorkLogCat(workLogCat);
        }

        if (com.useeinfo.framework.sugar.func.lang.StringUtils.isNotBlank(workLogLevelId)) {
            DictInfo workLogLevel = dictInfoBiz.findModel(StringConverters.null2Long(workLogLevelId));
            repairWorkLog.setWorkLogLevel(workLogLevel);
        }

        if (com.useeinfo.framework.sugar.func.lang.StringUtils.isNotBlank(repairOrderId)) {
            RepairOrder repairOrder = repairOrderBiz.findModel(StringConverters.null2Long(repairOrderId));
            repairWorkLog.setRepairOrder(repairOrder);
        }
        repairWorkLogBiz.addOrUpdate(repairWorkLog);
        return ResultUtil.success();
    }

    /**
     * 工单日志列表接口
     *
     * @param pageIndex     页数
     * @param pageSize      条数
     * @param repairOrderId 报修单id
     * @return
     */
    public ResultDto repairWorkLogList(String pageIndex, String pageSize, String repairOrderId) {
        QueryParam queryParam = new QueryParam(pageIndex, pageSize);
        if (com.useeinfo.framework.sugar.func.lang.StringUtils.isNotBlank(repairOrderId)) {
            queryParam.getSqlMap().put("repairOrderId", repairOrderId);
        }
        return ResultUtil.success(repairWorkLogBiz.findJSONList(queryParam));
    }

    /**
     * 工单日志详情接口
     *
     * @param repairWorkLogId 工作日志id
     * @return
     */
    public ResultDto repairWorkLogDetail(String repairWorkLogId) {
        if (com.useeinfo.framework.sugar.func.lang.StringUtils.isBlank(repairWorkLogId)) {
            return ResultUtil.error("参数错误");
        }
        RepairWorkLog repairWorkLog = repairWorkLogBiz.findModel(StringConverters.null2Long(repairWorkLogId));
        return ResultUtil.success(repairWorkLog.toJSONObjectDetail());
    }

    /**
     * 接单接口
     *
     * @param repairOrderId 报修单id
     * @return
     */
    public ResultDto taking(String repairOrderId) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        RepairOrder repairOrder = repairOrderBiz.findModel(StringConverters.null2Long(repairOrderId));
        if (repairOrder == null) {
            return ResultUtil.error();
        }
        //修改维修单状态
        repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.WAIT_PRESENCE);
        repairOrder.setReceiveUser(systemUser);
        repairOrder.setReceiveDate(new Date());
        repairOrderBiz.addOrUpdate(repairOrder);
        //日志
        repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.TAKING, sessionEnterprise, null);
        return ResultUtil.success();
    }

    /**
     * 到场接口
     *
     * @param presencePhotos 现场照片
     * @param repairOrderId  报修单id
     * @param longitude      经度
     * @param latitude       纬度
     * @return
     */
    public ResultDto presence(String presencePhotos, String repairOrderId, String longitude, String latitude) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

        if (StringUtils.isBlank(presencePhotos)) {
            return ResultUtil.error("请先拍照");
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("id", repairOrderId);
        List<RepairOrder> repairOrders = repairOrderBiz.findList(queryParam);
        if (CollectionUtils.isEmpty(repairOrders)) {
            return ResultUtil.error("请传入正确的参数");
        }

        JSONArray photos = JSONArray.parseArray(presencePhotos);
        Set<Resource> set = new HashSet<>();
        for (Object object : photos) {
            Resource resource = resourceBiz.findModel(StringConverters.null2Long(object));
            resource.setEnterprise(sessionEnterprise);
            resource.setResourceName("到场照片");
            resourceBiz.addOrUpdate(resource);
            set.add(resource);
        }
        RepairOrder repairOrder = repairOrders.get(0);
        repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.WAIT_CONFIRM_FAULT);
        repairOrder.setPresencePhoto(set);
        repairOrder.setPresenceTime(new Date());
        repairOrder.setMark(false);
        if (StringUtils.isNotBlank(longitude) && StringUtils.isNotBlank(latitude)) {
            repairOrder.setLatitude(new BigDecimal(latitude));
            repairOrder.setLongitude(new BigDecimal(longitude));
        }
        repairOrderBiz.addOrUpdate(repairOrder);

        //日志
        repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.PRESENCE, sessionEnterprise, null);

        return ResultUtil.success();
    }

    /**
     * 上传文件
     *
     * @param file 文件
     * @param type mp3 录音文件 img 图片
     * @return
     */
    public ResultDto upload(MultipartFile file, String type) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (file == null || StringUtils.isBlank(type)) {
            return ResultUtil.error("参数错误");
        }
        Resource resource = new Resource();
        String savePath = "";
        if ("mp3".equals(type)) {
            savePath = FileUtils.fileUpload(file, ConstantKeyFilePath.REPAIR_MP3_DIR, ConstantKeyFilePath.REPAIR_MP3_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
            resource.setResourceName("设备报修录音");
            resource.setResourceTypeEnum(ResourceTypeEnum.MP3);
        } else if ("img".equals(type)) {
            savePath = FileUtils.fileUpload(file, ConstantKeyFilePath.REPAIR_IMG_DIR, ConstantKeyFilePath.REPAIR_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
            resource.setResourceName("设备报修图片");
            resource.setResourceTypeEnum(ResourceTypeEnum.IMG);
        }
        resource.setPath(savePath);
        resource.setEnterprise(sessionEnterprise);
        resource.setCreateDate(new Date());
        resourceBiz.addOrUpdate(resource);
        return ResultUtil.success(resource.toJSONObject());
    }

    /**
     * 临时保存
     * @param repairOrderId
     * @param spareParts
     * @param finishPhotos
     * @param unrepairReason
     * @param measure
     * @param faultReason
     * @param inRepairScope
     * @param troubleCatId
     * @param workingHours
     * @return
     */
    public ResultDto save(String repairOrderId, String spareParts, String finishPhotos, String unrepairReason, String measure, String faultReason, Boolean inRepairScope, String troubleCatId, String workingHours) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (StringUtils.isNotBlank(repairOrderId)) {
            RepairOrder repairOrder = repairOrderBiz.findModel(StringConverters.null2Long(repairOrderId));
            repairOrder.setMeasure(StringConverters.null2String(measure));
            repairOrder.setSpareParts(StringConverters.null2String(spareParts));
            repairOrder.setUnrepairReason(StringConverters.null2String(unrepairReason));
            repairOrder.setFaultReason(StringConverters.null2String(faultReason));
            repairOrder.setInRepairScope(StringConverters.null2Boolean(inRepairScope));
            if (StringUtils.isNotBlank(troubleCatId)) {
                repairOrder.setTroubleCat(troubleCatBiz.findModel(StringConverters.null2Long(troubleCatId)));
            }
            if (StringUtils.isNotBlank(finishPhotos)) {
                JSONArray photos = JSONArray.parseArray(finishPhotos);
                Set<Resource> set = new HashSet<>();
                for (Object object : photos) {
                    Resource resource = resourceBiz.findModel(StringConverters.null2Long(object));
                    resource.setEnterprise(sessionEnterprise);
                    resource.setResourceName("完成照片");
                    resourceBiz.addOrUpdate(resource);
                    set.add(resource);
                }
                repairOrder.setFinishPhoto(set);
            }
            repairOrder.setSaveTriggerTime(new Date());
            repairOrderBiz.addOrUpdate(repairOrder);
        }
        return ResultUtil.success();
    }

    /**
     * 保存指定人
     *
     * @param assignIds 用户id（Array）
     * @param orderId   维修单id
     * @return
     */
    public ResultDto assignUsers(String assignIds, String orderId) {
        SystemUser sessionUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == sessionUser || null == enterprise) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        JSONArray jsonArray = JSONArray.parseArray(assignIds);
        RepairOrder repairOrder = dao.findModel(StringConverters.null2Long(orderId));
        if(repairOrder==null){
            return ResultUtil.error("报修单不存在");
        }
        Set<SystemUser> systemUsers = new HashSet<>();
        for (Object id : jsonArray) {
            SystemUser systemUser = systemUserBiz.findModel(StringConverters.null2Long(id));
            if (systemUser != null) {
                systemUsers.add(systemUser);
            }
        }
        repairOrder.setAssign(Boolean.TRUE);
        repairOrder.setAssignTypeEnum(AssignTypeEnum.USER);
        repairOrder.setAssignUsers(systemUsers);
        dao.update(repairOrder);
        //操作日志
        repairOrderLogBiz.addLog(repairOrder, sessionUser, RepairOrderLogOperationEnum.ASSIGN_USER, enterprise, null);
        return ResultUtil.success();
    }

    /**
     * 保存指定岗位
     *
     * @param assignIds 岗位id（Array
     * @param orderId   维修单id
     * @return
     */
    public ResultDto assignPositions(String assignIds, String orderId) {
        SystemUser sessionUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == sessionUser || null == enterprise) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        JSONArray jsonArray = JSONArray.parseArray(assignIds);
        RepairOrder repairOrder = dao.findModel(StringConverters.null2Long(orderId));
        Set<Position> positions = new HashSet<>();
        for (Object id : jsonArray) {
            Position position = positionBiz.findModel(StringConverters.null2Long(id));
            if (positions != null) {
                positions.add(position);
            }
        }
        repairOrder.setAssign(Boolean.TRUE);
        repairOrder.setAssignTypeEnum(AssignTypeEnum.POSITION);
        repairOrder.setAssignPositions(positions);
        dao.update(repairOrder);
        //操作日志
        repairOrderLogBiz.addLog(repairOrder, sessionUser, RepairOrderLogOperationEnum.ASSIGN_POSITION, enterprise, null);
        return ResultUtil.success();
    }

    /**
     * 审批
     *
     * @param repairOrderId 报修单id
     * @param type          true：审核通过 、 false：审核驳回
     * @param remark        备注
     * @return
     */
    public ResultDto audit(String repairOrderId, Boolean type, String remark) {
        String content = "";
        JSONObject jsonObject = new JSONObject();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        RepairOrder repairOrder = dao.findModel(StringConverters.null2Long(repairOrderId));
        JSONArray jsonArray = JSONArray.parseArray(repairOrder.getFlow());
        //审批通过
        if (type) {
            //维修单中的审批流快照
            int auditLevel = repairOrder.getAuditLevel();
            content = "维修单" + repairOrder.getReportCode() + "在第" + auditLevel + 1 + "级审核中,被" + systemUser.getUserName() + "审核通过。";
            if (jsonArray.size() > 0 && auditLevel + 1 < jsonArray.size()) {
                repairOrder.setAuditLevel(auditLevel + 1);
                repairOrder.setAuditUser(null);
                repairOrder.setAuditOrganization(null);
                repairOrder.setAuditPosition(null);
                JSONObject j = jsonArray.getJSONObject(auditLevel + 1);
                Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                repairOrder.setAuditOrganization(organizationBiz.findModel(organizationId));
                if ("POSITION".equals(nodeTypeEnum)) {
                    repairOrder.setAuditPosition(positionBiz.findModel(relationId));
                } else if ("USER".equals(nodeTypeEnum)) {
                    repairOrder.setAuditUser(systemUserBiz.findModel(relationId));
                } else {

                }
                jsonObject.put("final", false);
                repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.AUDIT, sessionEnterprise, null);
            } else if (jsonArray.size() > 0 && auditLevel + 1 == jsonArray.size()) {
                jsonObject.put("final", true);
                repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.COMPLETED);
                repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.AUDIT, sessionEnterprise, null);
                repairOrderLogBiz.addLog(repairOrder, repairOrder.getReceiveUser(), RepairOrderLogOperationEnum.FINISH, sessionEnterprise, null);
            }


        } else {
            content = "维修单" + repairOrder.getReportCode() + "在第" + repairOrder.getAuditLevel() + 1 + "级审核中,被" + systemUser.getUserName() + "驳回。";
            //退回重修
            jsonObject.put("final", false);
            repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.REJECTED);
            if (StringUtils.isBlank(remark)) {
                return ResultUtil.error("请输入驳回理由");
            }
            if (jsonArray.size() > 0) {
                repairOrder.setAuditUser(null);
                repairOrder.setAuditOrganization(null);
                repairOrder.setAuditPosition(null);
                repairOrder.setAuditLevel(0);
                JSONObject j = jsonArray.getJSONObject(0);
                Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                repairOrder.setAuditOrganization(organizationBiz.findModel(StringConverters.null2Long(organizationId)));
                if ("POSITION".equals(nodeTypeEnum)) {
                    repairOrder.setAuditPosition(positionBiz.findModel(StringConverters.null2Long(relationId)));
                } else if ("USER".equals(nodeTypeEnum)) {
                    repairOrder.setAuditUser(systemUserBiz.findModel(StringConverters.null2Long(relationId)));
                } else {

                }
            }
            repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.REJECT, sessionEnterprise, remark);

        }

        //推送消息
        SystemUser receiveUser = repairOrder.getReceiveUser();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("userId", StringConverters.null2String(receiveUser.getId()));
        List<UserDevice> userDevices = userDeviceBiz.findList(queryParam);
        List<MessageVO> messageVOS = new ArrayList<>();
        for (UserDevice userDevice : userDevices) {
            messageVOS.add(new MessageVO(userDevice.getDeviceType(), userDevice.getDeviceToken()));
        }
        if (CollectionUtils.isNotEmpty(messageVOS)) {
            ThreadUtils.sendDeviceMessages(messageVOS, content, MessageTypeEnum.REPAIR, messageBiz, StringConverters.null2String(sessionEnterprise.getId()),repairOrder.getReportCode());
        }

        repairOrderBiz.addOrUpdate(repairOrder);
        return ResultUtil.success(jsonObject);
    }


    /**
     * 巡检维修到场
     *
     * @param presencePhotos 到场照片（Array）
     * @param repairOrderId  维修单id
     * @param longitude      经度
     * @param latitude       纬度
     * @return
     */
    public ResultDto inspectionPresence(String presencePhotos, String repairOrderId, String longitude, String latitude) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

        if (StringUtils.isBlank(presencePhotos)) {
            return ResultUtil.error("请先拍照");
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("id", repairOrderId);
        List<RepairOrder> repairOrders = repairOrderBiz.findList(queryParam);
        if (CollectionUtils.isEmpty(repairOrders)) {
            return ResultUtil.error("请传入正确的参数");
        }

        JSONArray photos = JSONArray.parseArray(presencePhotos);
        Set<Resource> set = new HashSet<>();
        for (Object object : photos) {
            Resource resource = resourceBiz.findModel(StringConverters.null2Long(object));
            resource.setEnterprise(sessionEnterprise);
            resource.setResourceName("到场照片");
            resourceBiz.addOrUpdate(resource);
            set.add(resource);
        }
        RepairOrder repairOrder = repairOrders.get(0);
        if (repairOrder.getLevel() > 0 && StringUtils.isNotBlank(repairOrder.getFlow())) {
            repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.IN_AUDITING);
        } else {
            repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.COMPLETED);
        }
        repairOrder.setPresencePhoto(set);
        repairOrder.setPresenceTime(new Date());
        repairOrder.setMark(false);
        repairOrder.setRepairFinishTime(new Date());
        if (StringUtils.isNotBlank(longitude) && StringUtils.isNotBlank(latitude)) {
            repairOrder.setLatitude(new BigDecimal(latitude));
            repairOrder.setLongitude(new BigDecimal(longitude));
        }
        repairOrderBiz.addOrUpdate(repairOrder);

        //日志
        repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.PRESENCE, sessionEnterprise, null);

        return ResultUtil.success();
    }

    /**
     * 区域列表
     *
     * @param pageIndex   页数
     * @param pageSize    条数
     * @param searchParam 搜索项
     * @return
     */
    public ResultDto areaList(String pageIndex, String pageSize, String searchParam) {
        JSONObject result = new JSONObject();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        QueryParam queryParam = new QueryParam(pageIndex, pageSize);
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("magicLike", searchParam);
        List<Area> list = areaBiz.findList(queryParam);
        JSONArray jsonArray = new JSONArray();
        for (Area area : list) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", StringConverters.null2Long(area.getId()));
            String ids = area.getParentIds();
            StringBuilder names = new StringBuilder();
            if (StringUtils.isNotBlank(ids)) {
                String[] split = ids.split(",");
                for (String id : split) {
                    String name = areaBiz.findModel(StringConverters.null2Long(id)).getAreaName();
                    names.append(name).append("/");
                }
                names.append(area.getAreaName());
                jsonObject.put("names", names);
            } else {
                jsonObject.put("names", area.getAreaName());
            }
            jsonArray.add(jsonObject);
        }
        result.put("rows", jsonArray);
        return ResultUtil.success(result);
    }

    /**
     * 字典下拉选接口
     *
     * @param typeCode 类型编码
     * @return
     */
    public ResultDto getDictSelect(String typeCode) {
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        return ResultUtil.success(dictInfoBiz.getDictSelect(sessionEnterprise, typeCode));
    }

    /**
     * 根据单号获取维修单信息
     *
     * @param repairCode 维修单号
     * @return
     */
    public ResultDto getOrdersByCode(String repairCode) {
        JSONObject jsonObject = new JSONObject();
        JSONArray resultArray = new JSONArray();
        if (StringUtils.isNotBlank(repairCode)) {
            JSONArray jsonArray = JSONArray.parseArray(repairCode);
            for (Object object : jsonArray) {
                QueryParam queryParam = new QueryParam();
                queryParam.getSqlMap().put("reportCode", StringConverters.null2String(object));
                queryParam.getSqlMap().put("repairSource", RepairSourceEnum.WUHAN_GENERAL.getCode());
                List<RepairOrder> list = repairOrderBiz.findList(queryParam);
                if (CollectionUtils.isNotEmpty(list)) {
                    resultArray.add(list.get(0).toJSONObject());
                }
            }
        }
        jsonObject.put("rows", resultArray);
        return ResultUtil.success(jsonObject);
    }

    /**
     * 流程接口
     *
     * @param repairOrderId 报修单id
     * @return
     */
    public ResultDto process(String repairOrderId) {
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

        Map<String, String> queryHashMap = new HashMap<>();
        queryHashMap.put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryHashMap.put("repairOrderId", repairOrderId);
        queryHashMap.put("repairOrderLogOperation", "AUDIT");


        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("repairOrderId", repairOrderId);
        queryParam.setSqlOrder("order by id");
        List<RepairOrderLog> repairOrderLogs = repairOrderLogBiz.findList(queryParam);
        JSONArray jsonArray = new JSONArray();
        for (RepairOrderLog repairOrderLog : repairOrderLogs) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("createDate", CommonSugar.getTypedDefault(DateTimeUtils.formatDateToStringWithTime(repairOrderLog.getCreateDate()), ""));
            jsonObject.put("userName", StringConverters.null2String(repairOrderLog.getUserName()));
            if ("AUDIT".equals(repairOrderLog.getRepairOrderLogOperationEnum().getCode())) {
                for (int i = 0; i < repairOrderLogBiz.totalRecord(queryHashMap); i++) {
                    jsonObject.put("operation", NumberUtil.convert(++i) + "级" + repairOrderLog.getRepairOrderLogOperationEnum().getName());
                }

            } else {
                jsonObject.put("operation", repairOrderLog.getRepairOrderLogOperationEnum().getName());
            }
            jsonArray.add(jsonObject);
        }
        JSONObject result = new JSONObject();
        result.put("rows", jsonArray);
        return ResultUtil.success(result);
    }

    /**
     * 添加参与人
     *
     * @param repairOrderId 报修单id
     * @param partnerArray  参与人（Array）
     * @return
     */
    public ResultDto addPartner(String repairOrderId, String partnerArray) {
        JSONObject jsonObject = new JSONObject();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (StringUtils.isNotBlank(partnerArray)) {
            JSONArray array = JSONArray.parseArray(partnerArray);
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < array.size(); i++) {
                JSONObject j = array.getJSONObject(i);

                String userId = AliJsonObjectCover.ObjectString(j, "userId");

                QueryParam queryParam = new QueryParam();
                queryParam.getSqlMap().put("partnerId", userId);
                queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
                queryParam.getSqlMap().put("repairOrderId", repairOrderId);
                List<RepairPartner> list = repairPartnerBiz.findList(queryParam);
                RepairPartner repairPartner;
                if (CollectionUtils.isNotEmpty(list)) {
                    repairPartner = list.get(0);
                } else {
                    repairPartner = new RepairPartner();
                }


                if (StringUtils.isNotBlank(repairOrderId)) {
                    RepairOrder repairOrder = repairOrderBiz.findModel(StringConverters.null2Long(repairOrderId));
                    repairPartner.setRepairOrder(repairOrder);
                }
                repairPartner.setEnterprise(sessionEnterprise);
                String reason = AliJsonObjectCover.ObjectString(j, "reason");
                if (StringUtils.isNotBlank(reason)) {
                    repairPartner.setReason(reason);
                }
                String teamworkCatId = AliJsonObjectCover.ObjectString(j, "teamworkCatId");
                if (StringUtils.isNotBlank(teamworkCatId)) {
                    QueryParam dictInfoParam = new QueryParam();
                    dictInfoParam.getSqlMap().put("dictInfoId", StringConverters.null2String(teamworkCatId));
                    dictInfoParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise));
                    repairPartner.setTeamworkCat(CollectionUtils.isEmpty(dictInfoBiz.findList(dictInfoParam)) ? null : dictInfoBiz.findList(dictInfoParam).get(0));
                }

                if (StringUtils.isNotBlank(userId)) {
                    repairPartner.setPartner(systemUserBiz.findModel(StringConverters.null2Long(userId)));
                }

                repairPartnerBiz.addOrUpdate(repairPartner);
                jsonArray.add(repairPartner.getId());
            }
            jsonObject.put("partnerIds", jsonArray);
        }
        return ResultUtil.success(jsonObject);
    }

    /**
     * 移除参与人
     *
     * @param id 对应详情 partnerId
     * @return
     */
    public ResultDto removePartner(String id) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        repairPartnerBiz.deleteLogic(repairPartnerBiz.findModel(StringConverters.null2Long(id)));
        return ResultUtil.success();
    }

    /**
     * 终审评分
     *
     * @param repairOrderId 报修单id
     * @param remark        备注
     * @param score         评分
     * @return
     */
    public ResultDto finalAudit(String repairOrderId, String remark, String score) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        RepairOrder repairOrder = repairOrderBiz.findModel(StringConverters.null2Long(repairOrderId));
        repairOrder.setLastRemark(StringConverters.null2String(remark));
        repairOrder.setLastScore(StringConverters.null2Int(score));
        repairOrderBiz.addOrUpdate(repairOrder);
        return ResultUtil.success();
    }

    /**
     * 确认故障
     *
     * @param repairOrderId 报修单id
     * @param troubleCatId  故障分类id
     * @param faultReason   故障原因
     * @param inRepairScope 是否巡检范围
     * @return
     */
    public ResultDto confirmFault(String repairOrderId, String troubleCatId, String faultReason, Boolean inRepairScope) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

        if (StringUtils.isBlank(repairOrderId)) {
            return ResultUtil.error("请传入正确的参数");
        }

        QueryParam orderParam = new QueryParam();
        orderParam.getSqlMap().put("id", repairOrderId);
        orderParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        List<RepairOrder> repairOrders = repairOrderBiz.findList(orderParam);
        if (CollectionUtils.isEmpty(repairOrders)) {
            return ResultUtil.error();
        }

        RepairOrder repairOrder = repairOrders.get(0);

        if (StringUtils.isNotBlank(troubleCatId)) {
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("troubleCatId", troubleCatId);
            queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
            List<TroubleCat> troubleCats = troubleCatBiz.findList(queryParam);
            if (CollectionUtils.isNotEmpty(troubleCats)) {
                repairOrder.setTroubleCat(troubleCats.get(0));
            }
        }

        repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.UNFINISHED);
        repairOrder.setInRepairScope(StringConverters.null2Boolean(inRepairScope));
        repairOrder.setFaultReason(StringConverters.null2String(faultReason));
        repairOrderBiz.addOrUpdate(repairOrder);

        //日志
        repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.CONFIRM_FAULT, sessionEnterprise, null);
        return ResultUtil.success();
    }

    /**
     * 维修-确认完成
     *
     * @param repairOrder       维修单
     * @param participantInputs
     * @param spareParts
     * @param finishPhotos
     * @param unrepairReason
     * @param measure
     * @param repairFinishTime
     * @param faultReason
     * @param inRepairScope
     * @param troubleCatId
     * @return
     */
    public ResultDto repairConfirm(RepairOrder repairOrder, JSONArray participantInputs, String spareParts, String finishPhotos, String unrepairReason, String measure, String repairFinishTime, String faultReason, Boolean inRepairScope, String troubleCatId) {

        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (repairOrder == null) {
            return ResultUtil.error("维修不存在！");
        }

        if (StringUtils.isNotBlank(finishPhotos)) {
            JSONArray photos = JSONArray.parseArray(finishPhotos);
            Set<Resource> set = new HashSet<>();
            for (Object object : photos) {
                Resource resource = resourceBiz.findModel(StringConverters.null2Long(object));
                resource.setEnterprise(sessionEnterprise);
                resource.setResourceName("完成照片");
                resourceBiz.addOrUpdate(resource);
                set.add(resource);
            }
            repairOrder.setFinishPhoto(set);
        }
        repairOrder.setInRepairScope(StringConverters.null2Boolean(inRepairScope));
        if (StringUtils.isNotBlank(repairFinishTime)) {
            repairOrder.setRepairFinishTime(DateTimeUtils.parse("yyyy-MM-dd HH:mm:ss", repairFinishTime));
        }

        if (StringUtils.isNotBlank(troubleCatId)) {
            repairOrder.setTroubleCat(troubleCatBiz.findModel(StringConverters.null2Long(troubleCatId)));
        }

        long totalWorkingHours = repairOrder.getTotalWorkingHours();

        repairOrder.setUnrepairReason(StringConverters.null2String(faultReason));
        repairOrder.setSpareParts(StringConverters.null2String(spareParts));
        repairOrder.setUnrepairReason(StringConverters.null2String(unrepairReason));
        repairOrder.setMeasure(StringConverters.null2String(measure));

        if (repairOrder.getLevel() > 0 && StringUtils.isNotBlank(repairOrder.getFlow())) {
            repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.IN_AUDITING);
        } else {
            repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.COMPLETED);
        }

//        if(repairOrder.getSaveTriggerTime() != null){
//            long diffMinutesTime = DateTimeUtils.getDiffMinutesTime(repairOrder.getSaveTriggerTime(), new Date());
//            repairOrder.setWorkingHours(diffMinutesTime + repairOrder.getWorkingHours());
//        }else{
//            repairOrder.setWorkingHours(DateTimeUtils.getDiffMinutesTime(repairOrder.getPresenceTime(),new Date()));
//        }
        long thisHours=DateTimeUtils.newGetDiffMinutesTime(DateTimeUtils.parse("yyyy-MM-dd HH:mm:ss", DateTimeUtils.format(repairOrder.getPresenceTime(), "yyyy-MM-dd HH:mm:ss")), new Date());
        repairOrder.setWorkingHours(repairOrder.getWorkingHours()+thisHours);

        List<RepairPartner> repairPartners = new ArrayList<>();
        if (participantInputs.size() > 0) {
            for (int i = 0; i < participantInputs.size(); i++) {
                JSONObject j = participantInputs.getJSONObject(i);
                Long workingHours = AliJsonObjectCover.ObjectLong(j, "workingHours");
                if (workingHours == null) {
                    return ResultUtil.error("工时不能为空！");
                }
                totalWorkingHours += workingHours;
                Long partnerId = AliJsonObjectCover.ObjectLong(j, "userId");
                QueryParam q = new QueryParam();
                q.getSqlMap().put("partnerId", partnerId == null ? "-1" : partnerId + "");
                q.getSqlMap().put("repairOrderId", repairOrder.getId() + "");
                q.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
                List<RepairPartner> repairPartnerList = repairPartnerBiz.findList(q);
                if (CollectionUtils.isEmpty(repairPartnerList)) {
                    return ResultUtil.error("参与人不存在！");
                }
                RepairPartner repairPartner = repairPartnerList.get(0);
                repairPartner.setWorkingHours(repairPartner.getWorkingHours() + workingHours);
                repairPartners.add(repairPartner);
            }
        }
        repairOrder.setTotalWorkingHours(totalWorkingHours+thisHours);
        repairOrder.setRepairFinishTime(new Date());
        repairOrderBiz.addOrUpdate(repairOrder);
        repairPartners.forEach(repairPartner -> repairPartnerBiz.addOrUpdate(repairPartner));
        repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.COMPLETE, sessionEnterprise, null);


        //消息推送
        String auditAuthority = "ROLE_AUTO_REPAIR_ORDER_AUDIT";
        String content = "工单:" + repairOrder.getReportCode() + "已完成,待审核";
        List<UserDevice> userDevices = new ArrayList<>();
        List<SystemUser> systemUsers = new ArrayList<>();
        List<SystemUser> users = new ArrayList<>();

        if (repairOrder.getFlow() != null) {
            JSONArray jsonArray = JSONArray.parseArray(repairOrder.getFlow());
            if (jsonArray.size() > 0) {
                JSONObject j = jsonArray.getJSONObject(0);
                Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                Organization organization = organizationBiz.findModel(StringConverters.null2Long(organizationId));
                Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                if ("POSITION".equals(nodeTypeEnum)) {
                    systemUsers = dao.confirmSendUser(sessionEnterprise, positionBiz.findModel(StringConverters.null2Long(relationId)), organization, null);
                } else if ("USER".equals(nodeTypeEnum)) {
                    systemUsers = dao.confirmSendUser(sessionEnterprise, null, organization, systemUserBiz.findModel(StringConverters.null2Long(relationId)));
                }

                for (SystemUser systemUser1 : systemUsers) {
                    if (systemAuthorityBiz.hasAuthAuthority(auditAuthority, systemUser1.getId(), sessionEnterprise.getId())) {
                        users.add(systemUser1);
                    }
                }

                for (SystemUser systemUser1 : users) {
                    QueryParam queryParam = new QueryParam();
                    queryParam.getSqlMap().put("userId", StringConverters.null2String(systemUser1.getId()));
                    userDevices.addAll(userDeviceBiz.findList(queryParam));
                }

                List<MessageVO> messageVOS = new ArrayList<>();
                for (UserDevice userDevice : userDevices) {
                    messageVOS.add(new MessageVO(userDevice.getDeviceType(), userDevice.getDeviceToken()));
                }
                if (CollectionUtils.isNotEmpty(messageVOS)) {
                    ThreadUtils.sendDeviceMessages(messageVOS, content, MessageTypeEnum.REPAIR, messageBiz, StringConverters.null2String(sessionEnterprise.getId()),repairOrder.getReportCode());
                }
            }
        }


        return ResultUtil.success();
    }

    /**
     * 维修历史纪录
     *
     * @param facilityId 设备id
     * @param pageIndex  页码
     * @param pageSize   页数
     * @return
     */
    public ResultDto repairHistory(String facilityId, String pageIndex, String pageSize) {
        JSONObject result = new JSONObject();
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        QueryParam queryParam = new QueryParam(pageIndex, pageSize);
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("facilityId", facilityId);
        queryParam.getSqlMap().put("repairOrderStatus", "COMPLETED");
        List<RepairOrder> list = repairOrderBiz.findList(queryParam);

        JSONArray rows = new JSONArray();
        for (RepairOrder repairOrder : list) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("createDate", DateTimeUtils.format(repairOrder.getCreateDate(), DateTimeUtils.format(repairOrder.getCreateDate(), "MM-dd HH:mm")));
            jsonObject.put("reportContent", StringConverters.null2String(repairOrder.getReportContent()));
            jsonObject.put("reportAddress", StringConverters.null2String(repairOrder.getReportAddress()));
            jsonObject.put("orderStatus", repairOrder.getRepairOrderStatusEnum().getName());
            jsonObject.put("reportCode", repairOrder.getReportCode());
            jsonObject.put("reportUser", repairOrder.getReportUser() == null ? "" : repairOrder.getReportUser().getUserName());
            jsonObject.put("id", repairOrder.getId());

            //标签设置
            Date now = new Date();
            JSONArray tags = new JSONArray();
            JSONObject tagObject = new JSONObject();
            if (now.getTime() > repairOrder.getRequireFinishTime().getTime()) {
                tags.add(tagObject("逾期", "full-orange"));
            }
            if (repairOrder.getReportLevel() != null) {
                tags.add(tagObject(repairOrder.getReportLevel().getGrade(), "orange"));
            }

            if (repairOrder.getAssign()) {
                tags.add(tagObject("被指派", "blue"));
            }

            if ("IN_AUDITING".equals(repairOrder.getRepairOrderStatusEnum().getCode())) {
                tags.add(tagObject(NumberUtil.convert(repairOrder.getAuditLevel() + 1) + "审", "blue"));
            }
            if (StringUtils.isNotBlank(repairOrder.getRepairOrderTypeEnum().getCode())) {
                if ("COMMON_ORDER".equals(repairOrder.getRepairOrderTypeEnum().getCode())) {
                    tags.add(tagObject("普通", "blue"));
                } else if ("FACILITY_ORDER".equals(repairOrder.getRepairOrderTypeEnum().getCode())) {
                    tags.add(tagObject("设备", "blue"));
                }
            }
            if (repairOrder.getReportMajor() != null) {
                tags.add(tagObject(repairOrder.getReportMajor().getPropertyName(), "blue"));
            }

            //设备标签
            if (repairOrder.getFacility() != null && repairOrder.getFacility().getFacilityCat() != null) {
                FacilityCat rootCat = facilityCatBiz.findRootCat(repairOrder.getFacility().getFacilityCat().getId());
                tags.add(tagObject(repairOrder.getFacility().getFacilityCat().getCatName(), "blue"));
                tags.add(tagObject(rootCat.getCatName(), "blue"));
            }
            jsonObject.put("tags", tags);
            rows.add(jsonObject);
        }
        result.put("rows", rows);
        Map<String, String> queryHashMap = new HashMap<>();
        queryHashMap.put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryHashMap.put("facilityId", facilityId);
        queryHashMap.put("repairOrderStatus", "COMPLETED");
        result.put("records", repairOrderBiz.totalRecord(queryHashMap));
        return ResultUtil.success(result);
    }

    private JSONObject tagObject(String name, String color) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", name);
        jsonObject.put("color", color);
        return jsonObject;
    }

    /**
     * 转单
     *
     * @param repairOrderId 报修单id
     * @param userIds       用户id（Array）
     * @return
     */
    public ResultDto transfer(String repairOrderId, String userIds) {
        List<SystemUser> users = new ArrayList<>();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        RepairOrder repairOrder = repairOrderBiz.findModel(StringConverters.ToLong(repairOrderId));
        String content = "工单:" + repairOrder.getReportCode() + "被转单,待接单";
        JSONArray jsonArray = JSONArray.parseArray(userIds);
        if (jsonArray.size() > 0) {
            repairOrder.setAssignPositions(null);
            repairOrder.setAssignUsers(null);
            repairOrder.setAssignTypeEnum(AssignTypeEnum.USER);
            repairOrder.setAssign(true);
            repairOrder.setTransfer(true);
            Set<SystemUser> user = new HashSet<>();
            users.addAll(user);
            for (Object id : jsonArray) {
                SystemUser model = systemUserBiz.findModel(StringConverters.null2Long(id));
                user.add(model);
            }
            repairOrder.setAssignUsers(user);
        }
        repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.WAIT_TAKING);
        repairOrderBiz.addOrUpdate(repairOrder);
        repairOrderLogBiz.addLog(repairOrder, systemUser, RepairOrderLogOperationEnum.TRANSFER, sessionEnterprise, null);


        //推送消息
        List<UserDevice> userDevices = new ArrayList<>();
        for (SystemUser systemUser1 : users) {
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("userId", StringConverters.null2String(systemUser1.getId()));
            userDevices.addAll(userDeviceBiz.findList(queryParam));
        }
        List<MessageVO> messageVOS = new ArrayList<>();
        for (UserDevice userDevice : userDevices) {
            messageVOS.add(new MessageVO(userDevice.getDeviceType(), userDevice.getDeviceToken()));
        }
        if (CollectionUtils.isNotEmpty(messageVOS)) {
            ThreadUtils.sendDeviceMessages(messageVOS, content, MessageTypeEnum.REPAIR, messageBiz, StringConverters.null2String(sessionEnterprise.getId()),repairOrder.getReportCode());
        }

        return ResultUtil.success();
    }

    /**
     * 转单列表
     *
     * @param searchParam 搜索项
     * @param pageIndex   页码
     * @param pageSize    条数
     * @return
     */
    public ResultDto transferList(String searchParam, String pageIndex, String pageSize) {
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        return ResultUtil.success(dao.autoTransferList(searchParam, pageIndex, pageSize, systemUser, sessionEnterprise));
    }

    /**
     * 指派人员列表
     *
     * @param pageIndex 页数
     * @param pageSize  条数
     * @param userName  用户名
     * @param userIds   用户id
     * @return
     */
    public ResultDto getUser(String pageIndex, String pageSize, String userName, String userIds) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == enterprise) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        QueryParam queryParam = new QueryParam(pageIndex, pageSize);
        String userHql = "select obj from SystemUser obj where obj.deleteStatus is false and obj.operationRole='common' and " +
                "exists( select er from obj.enterpriseSet er" +
                " where er.id=" + enterprise.getId() + ")";
        if (!StringConverters.null2String(userName).equals("")) {
            userHql += " and obj.userName like '%" + userName + "%'";
        }

        if (!StringConverters.null2String(userIds).equals("")) {
            String ids = "";
            for (Object object : JSONArray.parseArray(userIds)) {
                if (ids.equals("")) {
                    ids = StringConverters.null2String(object);
                } else {
                    ids += "," + StringConverters.null2String(object);
                }
            }
            if (!StringConverters.null2String(ids).equals("")) {
                userHql += "  and obj.id not in(" + StringConverters.null2String(ids) + ")";
            }

        }
        JSONArray jsonArray = new JSONArray();
        for (SystemUser systemUser : systemUserBiz.hqlExcute(userHql, queryParam)) {
            jsonArray.add(systemUser.toJSONObject());
        }
        return ResultUtil.success(jsonArray);
    }

    /**
     * 指派岗位列表
     *
     * @param pageIndex
     * @param pageSize
     * @param positionIds
     * @return
     */
    public ResultDto getPosition(String pageIndex, String pageSize, String positionIds) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == enterprise) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        QueryParam queryParam = new QueryParam(pageIndex, pageSize);
        String posHql = "select obj from Position obj where obj.deleteStatus is false and obj.enterprise.id=" + enterprise.getId();
        if (!StringConverters.null2String(positionIds).equals("")) {
            String ids = "";
            for (Object object : JSONArray.parseArray(positionIds)) {
                if (ids.equals("")) {
                    ids = StringConverters.null2String(object);
                } else {
                    ids += "," + StringConverters.null2String(object);
                }
            }
            if (!StringConverters.null2String(ids).equals("")) {
                posHql += "  and obj.id not in(" + StringConverters.null2String(ids) + ")";
            }

        }
        JSONArray jsonArray = new JSONArray();
        for (Position position : positionBiz.hqlExcute(posHql, queryParam)) {
            jsonArray.add(position.toJSONObject());
        }
        return ResultUtil.success(jsonArray);
    }

    /**
     * 参与人详情
     *
     * @param repairOrderId 报修单id
     * @param userId        用户id
     * @return
     */
    public ResultDto partnerDetail(String repairOrderId, String userId) {
        JSONObject result = new JSONObject();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("partnerId", userId);
        queryParam.getSqlMap().put("repairOrderId", repairOrderId);
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        List<RepairPartner> repairPartners = repairPartnerBiz.findList(queryParam);
        if (CollectionUtils.isNotEmpty(repairPartners)) {
            result = repairPartners.get(0).toJSONObject();
        }
        return ResultUtil.success(result);
    }


    /**
     * 报警数据开始新增到维修单中
     *
     * @param warningDetail
     */
    @Transactional
    public Boolean warningSaveToRepairOrder(WarningDetail warningDetail, Enterprise enterprise) {
        try {
            if (enterprise == null || warningDetail == null || warningDetail.getWarning() == null) {
                return false;
            }
            QueryParam queryParam = new QueryParam(1, 1);
            queryParam.getSqlMap().put("applicationName", autoIntAuditFlow);
            List<AuditFlow> auditFlows = auditFlowBiz.findList(queryParam);
            Warning warning = warningDetail.getWarning();
            RepairOrder repairOrder = new RepairOrder();
            repairOrder.setEnterprise(enterprise);
            repairOrder.setReportCode(this.getCode(StringConverters.null2String(enterprise.getId())));
            repairOrder.setRepairOrderStatusEnum(RepairOrderStatusEnum.WAIT_TAKING);
            repairOrder.setRepairSourceEnum(RepairSourceEnum.WUHAN_GENERAL);
            repairOrder.setRepairOrderTypeEnum(RepairOrderTypeEnum.AUTOMATIC_REPAIR);
            repairOrder.setReportAddress(warning.getPosition());
            repairOrder.setReportContent(warning.getContent());
            WarningGroup warningGroup = CommonSugar.getTypedDefault(warning.getWarningGroup(), new WarningGroup());
//            repairOrder.setReportArea(warningGroup.getReportArea());
            repairOrder.setReportLevel(repairLevelBiz.getRepairLevel(warning.getLevel()));
//            repairOrder.setReportLevel(repairLevelBiz.getRepairLevel(warningDetail.getWuHanPoint().getLvl()));
            if (CollectionUtils.isNotEmpty(auditFlows)) {
                AuditFlow auditFlow1 = auditFlows.get(0);
                repairOrder.setAuditFlow(auditFlow1);
                repairOrder.setLevel(auditFlow1.getLevel());
                repairOrder.setFlow(auditFlow1.getFlow());
                repairOrder.setFlowName(auditFlow1.getFlowName());
                JSONArray jsonArray = JSON.parseArray(auditFlow1.getFlow());
                if (jsonArray != null && jsonArray.size() > 0) {
                    repairOrder.setAuditOrganization(null);
                    repairOrder.setAuditUser(null);
                    repairOrder.setAuditPosition(null);
                    JSONObject j = jsonArray.getJSONObject(0);
                    Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                    Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                    String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                    repairOrder.setAuditOrganization(organizationBiz.findModel(organizationId));
                    if ("POSITION".equals(nodeTypeEnum)) {
                        repairOrder.setAuditPosition(positionBiz.findModel(relationId));
                    } else if ("USER".equals(nodeTypeEnum)) {
                        repairOrder.setAuditUser(systemUserBiz.findModel(relationId));
                    }
                }
            }
            dao.warningAdd(repairOrder);
            return true;
        } catch (Exception e) {
        }
        return false;
    }


    public String getCode(String enterpriseId) {
        return dao.getCode(enterpriseId);
    }
}
